package com.lsj.provider;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class MyDaoAuthenticationProvider extends DaoAuthenticationProvider {


    /*DaoAuthenticationProvider最常用于从数据库加载用户信息进行验证，该类的大部分方法已经由其父类实现，
    * 其中主要的认证方法authenticate已经由其父类完成，但是由于每个认证器的验证密码的方式不尽相同，所以留下了抽象方法additionalAuthenticationChecks()
    * 由DaoAuthenticationProvider子类完成，我们在这里添加我们自己的逻辑，例如验证码的校验，或者是当前流行的手机验证码登录方式*/
    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        //RequestContextHolder是springmvc提供的API，可以获取到当前的request
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String code = request.getParameter("code");
        String verify_code = (String) request.getSession().getAttribute("verify_code");
        if(StringUtils.isEmpty(code) || !verify_code.equals(code)){
            throw new AuthenticationServiceException("验证码错误！");
        }
        super.additionalAuthenticationChecks(userDetails, authentication);
    }
}
